package com.xdkj.web.servlet;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * ClassName BaseServlet
 * Description:
 *
 * @Author:一尘
 * @Version:1.0
 * @Date:2021-11-02-10:32
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受参数
        String action = req.getParameter("action");
        Method method = null;
        try {
            method = this.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            Object invoke = method.invoke(this, req, resp);
            if (invoke != null) {
                // 是不是字符串
                if (invoke instanceof String) {
                    String result = (String) invoke;
                    if (result.startsWith("/")) {
                        //跳转
                        resp.setContentType("text/html;charset=utf8");
                        req.getRequestDispatcher(result).include(req, resp);
                    } else {
                        resp.setContentType("text/html;charset=utf8");
                        resp.sendRedirect(result);
                    }
                } else {
                    //响应json数据
                    Gson gson = new Gson();
                    String s = gson.toJson(invoke);
                    resp.setContentType("application/json;charset=utf8");
                    resp.getOutputStream().write(s.getBytes());
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }
}
